<template>
    <div>
        <!-- 搜索参数 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="公告标题" class="bold-label">
                        <el-input v-model="params.noticeTitle" clearable placeholder="请输入公告标题"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="操作人员" class="bold-label">
                        <el-input v-model="params.created" clearable placeholder="请输入操作人员"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="类型" class="bold-label">
                        <el-select v-model="params.noticeType" placeholder="请选择类型">
                            <el-option label="公告" value="0"></el-option>
                            <el-option label="通知" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button :icon="Refresh" @click="resetParams">重置</el-button>
                </el-col>
            </el-row>
        </el-form>
        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" plain :icon="Plus" @click="openNotice">新增</el-button>
                    <el-button type="success" plain :disabled="updateDisabled" :icon="EditPen" @click="openUpdateNotice">修改</el-button>
                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDelete">删除</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>
        <!-- 表格数据 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="55" :selectable="selectable" />
                <el-table-column align="center" prop="noticeId" label="序号" width="120" />
                <el-table-column align="center" prop="noticeTitle" label="公告标题" />
                <el-table-column align="center" prop="noticeType" label="公告类型">
                    <template #default="scope">
                        <el-tag :type="scope.row.noticeType === '0' ? 'success' : 'warning'">
                            {{ scope.row.noticeType === '0' ? '公告' : '通知' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="noticeStatus" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.noticeStatus === '0' ? 'primary' : 'danger'">
                            {{ scope.row.noticeStatus === '0' ? '正常' : '关闭' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="created" label="创建者" />
                <el-table-column align="center" prop="noticeCreateTime" label="创建时间" />
                <el-table-column align="center" label="操作">
                    <template #default="scope">
                        <el-button link type="primary" size="small" :icon="EditPen"
                            @click="updateRow(index, scope.row)">修改</el-button>
                        <el-button link type="primary" size="small" :icon="Delete"
                            @click="deleteRow(index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination v-model:current-page="params.currentPage" v-model:page-size="params.pageSize"
                        background :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResult.total)"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>
        <!-- 弹窗层组件 -->
        <el-dialog :title="title" v-model="dialogVisible" @close="handleClose" draggable>
            <!-- 表单数据项 -->
            <el-form :model="formData">
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="公告标题" class="bold-label">
                            <el-input v-model="formData.noticeTitle" clearable placeholder="请输入公告标题"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="公告类型" class="bold-label">
                            <el-select v-model="formData.noticeType" placeholder="请选择类型">
                                <el-option label="公告" value="0"></el-option>
                                <el-option label="通知" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="状态" class="bold-label">
                            <el-radio-group v-model="formData.noticeStatus">
                                <el-radio value="0">正常</el-radio>
                                <el-radio value="1">关闭</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="公告内容" class="bold-label">
                            <el-input v-model="formData.noticeContent" class="notice-textarea"
                                :autosize="{ minRows: 10, maxRows: 10 }" type="textarea" placeholder="请输入公告内容" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Delete, Search, Refresh, Plus, EditPen } from '@element-plus/icons-vue'
import { findNotice, updateNotice, insertNotice, deleteNotice, sendMessage } from '@/apis/index'
import { ElMessage, ElNotification } from 'element-plus'
import { getUserInfo } from '@/utils/index'
import send from '@/assets/send.json'
const params = ref({
    currentPage: 1,
    pageSize: 2,
    noticeTitle: '',
    created: '',
    noticeType: ''
})
const tableData = ref([])   // 表格数据
const pageResult = ref({}) // 表格分页数据
const deleteDisabled = ref(true) // 控制删除按钮是否禁用
const updateDisabled = ref(true) // 控制修改按钮是否禁用
const noticeIds = ref([]) // 选中行的noticeIds数组
// 分页大小
const pageSizes = [2, 5, 8, 10]
const title = ref('') // 弹窗标题
const dialogVisible = ref(false) // 弹窗显示状态
const formData = ref({
    noticeStatus: "0",
    created: getUserInfo(localStorage.getItem('token'))
}) // 弹窗表单数据

onMounted(async () => {
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
})
/**
 * 删除单行数据
 * @param index 行索引
 * @param row 行数据
 */
const deleteRow = async (index, row) => {
    noticeIds.value.push(row.noticeId)
    console.log(noticeIds.value)
    await deleteNotice(noticeIds.value)
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
    ElMessage.success('删除成功')
}
/**
 * 批量删除选中行
 */
const handleDelete = async () => {
    await deleteNotice(noticeIds.value)
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
    ElMessage.success('删除成功')
}
/**
 * 单行修改
 * @param index 行索引
 * @param row 行数据
 */
const updateRow = (index, row) => {
    dialogVisible.value = !dialogVisible.value
    title.value = '修改公告'
    formData.value = { ...row }
}
/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}

/**
 * 处理选中行变化
 * @param val 选中行的数组
 */
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    updateDisabled.value = !(val.length === 1)
    if (!updateDisabled.value) {
        formData.value = { ...val[0] }
    } else {
        formData.value = { noticeStatus: "0", created: getUserInfo(localStorage.getItem('token')) }
    }
    noticeIds.value = val.map(item => item.noticeId) // 使用map方法过滤出选中行的logId数组
}

/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 重置参数
 */
const resetParams = () => {
    params.value = {
        currentPage: 1,
        pageSize: 2,
        noticeTitle: '',
        created: '',
        noticeType: ''
    }
}
/**
 * 搜索查询
 */
const handleSearch = async () => {
    pageResult.value = await findNotice(params.value)
    tableData.value = pageResult.value.records
}
// 弹窗关闭时重置表单数据
const handleClose = () => {
    formData.value = {
        noticeStatus: "0",
        created: getUserInfo(localStorage.getItem('token'))
    }
}
/**
 * 提交表单数据，新增或修改
 */
const handleSubmit = async () => {
    try {
        if (title.value == '添加公告') {
            await insertNotice(formData.value)
            send.content = `<h3>${formData.value.noticeTitle}</h3><br><p>${formData.value.noticeContent}</p>`
            const result = await sendMessage(JSON.stringify(send))
            if (result.code == 1000) {
                ElNotification({
                    title: 'ERP系统通知',
                    message: "通知成功!",
                    type: 'success',
                })
            } else {
                ElNotification({
                    title: 'ERP系统通知',
                    message: "通知失败!",
                    type: 'error',
                })
            }
        } else {
            await updateNotice(formData.value)
        }
        dialogVisible.value = !dialogVisible.value
        ElMessage.success(`${title.value}成功`)
        title.value = ''
        formData.value = { noticeStatus: "0", created: getUserInfo(localStorage.getItem('token')) }
        await handleSearch()
    } catch (error) {
        ElMessage.success("操作失败")
    }
}
/**
 * 打开新增弹窗
 */
const openNotice = () => {
    dialogVisible.value = !dialogVisible.value
    title.value = '添加公告'
}
/**
 * 打开修改弹窗
 */
const openUpdateNotice = () => {
    dialogVisible.value = !dialogVisible.value
    title.value = '修改公告'
}

</script>

<style scoped>
.bold-label {
    font-weight: bold;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}

.bold-label {
    font-weight: bold;
}

.notice-textarea .el-textarea__inner {
    width: 660px;
    height: 192px;
}
</style>
